<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="任务编号" prop="id">
        <el-input
            v-model="queryParams.id"
            placeholder="请输入任务编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>


      <el-form-item label="验证进程" prop="penetrationStatus" label-width="85px">
        <el-select
            v-model="queryParams.penetrationStatus"
            placeholder="请选择任务验证进程"
            clearable
            style="width: 240px"
            @change="getSelectChangeList">
          <el-option
              v-for="dict in sys_hit_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="研判进程" prop="analysisStatus" label-width="83px">
        <el-select
            v-model="queryParams.analysisStatus"
            placeholder="请选择任务研判进程"
            clearable
            style="width: 240px"
            @change="getSelectChangeList">
          <el-option
              v-for="dict in sys_hit_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="地区" prop="type">
        <el-cascader
            placeholder="请输入/选择地区"
            v-model="queryParams.area"
            :options="options"
            @change="handleChange"
            filterable
            clearable
            :props="{ checkStrictly: true }">
        </el-cascader>
      </el-form-item>


      <el-form-item label="创建时间" style="width: 308px;">
        <el-date-picker
            v-model="dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="getSelectChangeList">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="URL地址" prop="url" label-width="69px">
        <el-input
            v-model="queryParams.url"
            placeholder="请输入URL地址"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>



      <el-form-item label="任务类型" prop="parentTaskRadio" label-width="85px">
        <el-select
            v-model="queryParams.parentTaskRadio"
            placeholder="请选择任务类型"
            clearable
            style="width: 240px"
            @change="getSelectChangeList">
          <el-option
              v-for="dict in sys_task_status"
              :key="dict.value"
              :label="dict.label"
              :value="Number(dict.value)"/>
        </el-select>
      </el-form-item>

      <el-form-item label="IP地址" prop="ip" label-width="83px">
        <el-input
            v-model="queryParams.ip"
            placeholder="请输入IP地址"
            clearable
            @keyup.enter="handleQuery"
            style="width: 240px;"
        />
      </el-form-item>

      <el-form-item style="margin-left: 28px">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button
            type="primary"
            plain
            icon="Search"
            @click="handleTaskSearch"
            v-hasPermi="['system:task:list']">查询任务
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:task:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:task:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:task:remove']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Upload"
            @click="handleImport"
        >导入</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:task:export']"
        >导出</el-button>
      </el-col>


      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Plus"
            @click="subTask"
            :disabled="addTaskButton"
            v-hasPermi="['system:task:addSubTask']"
        >子任务关联</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            @click="deleteSubTask"
            :disabled="deleteTaskButton"
            v-hasPermi="['system:task:deleteSubTask']"
        >子任务取消关联</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Plus"
            @click="againGetIp('signle')"
            :disabled="againGetIpButton"
        >IP重新获取</el-button>
      </el-col>

<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="success"-->
<!--            plain-->
<!--            icon="Plus"-->
<!--            @click="againGetIp('all')"-->
<!--        >所有任务ip重新获取</el-button>-->
<!--      </el-col>-->

      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Plus"
            @click="changeList()"
        >数据显示切换</el-button>
      </el-col>
<!--v-show="changeListButton"-->

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="multipleTableRef"
        v-loading="loading" :data="taskList"
              @selection-change="handleSelectionChange"
              @row-click="rowClick">
      <el-table-column  type="selection" width="55" align="center" />
      <el-table-column  label="任务编号" align="center" prop="id" fixed width="180px">
        <template #default="scope">

          <span>
            <el-tag type="success" v-if="scope.row.parentTaskRadio==0">主任务</el-tag>
            <el-tag type="danger"  v-else-if="scope.row.parentTaskRadio==-1 && scope.row.parentTaskId==-1">子任务-未关联</el-tag>
            <el-tag  v-else-if="scope.row.parentTaskRadio==-1 && scope.row.parentTaskId!=-1">子任务-已关联</el-tag>

            {{scope.row.id}}
          </span>

        </template>
      </el-table-column>
      <el-table-column label="URL地址" align="center" prop="url" width="180px" fixed >

        <template #default="scope">
          <span>
            {{scope.row.url}}
            <el-icon>
              <CopyDocument @click="onCopy(scope.row.url,scope.row.id)"/>
            </el-icon>
          </span>
        </template>

      </el-table-column>

      <el-table-column label="验证进程" align="center" prop="penetrationStatus">
        <template #default="scope">
          <dict-tag :options="sys_hit_status" :value="scope.row.penetrationStatus" />
        </template>
      </el-table-column>

      <el-table-column label="验证跟进人" align="center" prop="penetrationFollowPerson" width="95px"/>

      <el-table-column label="验证状态" align="center" prop="penetrationStatusResult" width="160px">
        <template #default="scope">
          <el-tag >{{ getStatusName(scope.row.penetrationStatusResult) }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="验证完成时间" align="center" prop="penetrationEndTime" width="105">
        <template #default="scope">
          <span>{{ parseTime(scope.row.penetrationEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="研判进程" align="center" prop="analysisStatus" >
        <template #default="scope">
          <dict-tag :options="sys_hit_status" :value="scope.row.analysisStatus"/>
        </template>
      </el-table-column>

      <el-table-column label="研判跟进人" align="center" prop="analysisFollowPerson" width="95px" />

      <el-table-column label="研判状态" align="center" prop="analysisStatus">
        <template #default="scope">
          <el-tag v-if="scope.row.analysisStatus == 2">{{ "-----" }}</el-tag>
          <el-tag type="danger" v-else-if="scope.row.analysisStatus == 0">{{ "未完成" }}</el-tag>
          <el-tag type="success" v-else-if="scope.row.analysisStatus == 1">{{ "已完成" }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="研判完成时间" align="center" prop="analysisEndTime" width="105">
        <template #default="scope">
          <span>{{ parseTime(scope.row.analysisEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>


      <el-table-column label="省份" align="center" prop="province" />
      <el-table-column label="城市" align="center" prop="city" />
      <el-table-column label="区县" align="center" prop="county" width="135" />

      <el-table-column label="案件类型" align="center" width="120px" prop="type" >
        <template #default="scope">
          <el-tag >{{ getName(scope.row.type) }}</el-tag>
          <!--          {{ getName(scope.row.type) }}-->
        </template>
      </el-table-column>

      <el-table-column label="IP地址" align="center" prop="ip" width="120px"/>
      <el-table-column label="任务创建时间" align="center" prop="createTime" width="105">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务创建人" align="center" prop="createBy" width="90"/>



      <el-table-column label="加急状态" align="center" prop="priority" fixed="right">
        <template #default="scope">
          <dict-tag :options="sys_priority" :value="scope.row.priority" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="262px" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleDetails(scope.row)" v-hasPermi="['system:task:edit']">关联</el-button>
          <el-button link type="primary" icon="Edit" @click="handleSearch(scope.row)" v-hasPermi="['system:task:edit']">查看</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:task:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:task:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 关联任务对话框 -->
    <el-dialog :title="title2" v-model="addSubTask" width="650px" append-to-body :close-on-click-modal="false">


      <el-form v-if="title2=='子任务关联'" ref="taskRef" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="请选择主任务编号" >
          <el-select v-model="subTaskForm.parentTaskId" placeholder="请选择"
                     filterable
                     clearable>
            <el-option
                v-for="dict in masterTaskListValue"
                :key="dict.id"
                :label="dict.id"
                :value="dict.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>


      <el-form v-if="title2=='主任务关联'" ref="taskRef" :model="form" :rules="rules" label-width="140px" style="height: 100px">
        <el-form-item label="请选择子任务编号">

          <el-input v-model="subTaskForm.subTaskIds" placeholder="请输入子任务编号，多个用英文逗号分隔"
                    clearable>

          </el-input>


<!--          <el-select v-model="subTaskForm.subTaskIds"-->
<!--                     placeholder="请选择"-->
<!--                     filterable-->
<!--                     clearable-->
<!--                     multiple>-->

<!--            <el-option-->
<!--                v-for="dict in subTaskListValue"-->
<!--                :key="dict.id"-->
<!--                :label="dict.id"-->
<!--                :value="dict.id">-->
<!--            </el-option>-->


<!--          </el-select>-->
        </el-form-item>
      </el-form>


      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSubTask(title2)">确 定</el-button>
          <el-button @click="subTaskCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>






    <!-- 添加或修改任务对话框 -->
    <el-dialog :title="title" v-model="open" width="650px" append-to-body :close-on-click-modal="false">

      <el-form v-if="title=='添加任务'" ref="taskRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="提交单位" prop="source">
          <el-select v-model="form.source" placeholder="请选择提交单位"
                     filterable
                     clearable>
            <el-option
                v-for="dict in sourceList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="加急状态" prop="priority">
          <el-select v-model="form.priority" placeholder="请选择加急状态">
            <el-option
                v-for="dict in sys_priority"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="地区" prop="value">
          <el-cascader
              placeholder="请输入/选择地区"
              ref="fileRef"
              v-model="form.area"
              :options="options"
              @change="handleChange3"
              @visible-change="handleVisibleChange"
              filterable
              clearable
              :props="{ checkStrictly: true }"
              style="width: 530px">
          </el-cascader>
        </el-form-item>

        <el-form-item label="案件类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择案件类型"
                     filterable
                     clearable>
            <el-option
                v-for="dict in typeList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="提交方内部编号" prop="clientCode">
          <el-input v-model="form.clientCode" placeholder="请输入提交方内部编号" />
        </el-form-item>

        <el-form-item label="URL网址" prop="url">
          <el-input v-model="form.url" placeholder="请输入URL网址" />
        </el-form-item>
        <el-form-item label="IP地址" prop="ip">
          <el-input v-model="form.ip" placeholder="请输入IP地址" />
        </el-form-item>
      </el-form>


      <el-form v-if="title=='修改任务'" ref="taskRef" :model="form" :rules="rules" label-width="120px">

        <el-form-item label="加急状态" prop="priority">
          <el-select v-model="form.priority" placeholder="请选择加急状态">
            <el-option
                v-for="dict in sys_priority"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="地区" prop="value">
          <el-cascader
              ref="fileRef"
              placeholder="请输入/选择地区"
              v-model="form.area"
              :options="options"
              filterable
              clearable
              @change="handleChange3"
              style="width: 530px"
              :props="{ checkStrictly: true }">
          </el-cascader>
        </el-form-item>

        <el-form-item label="提交单位" prop="source">
          <el-select v-model="form.source" placeholder="请选择提交单位"
                     filterable
                     clearable>
            <el-option
                v-for="dict in sourceList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="案件类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择案件类型"
                     filterable
                     clearable>
            <el-option
                v-for="dict in typeList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="提交方内部编号" prop="clientCode">
          <el-input v-model="form.clientCode" placeholder="请输入提交方内部编号" />
        </el-form-item>


        <el-form-item label="URL网址" prop="url">
          <el-input v-model="form.url" placeholder="请输入URL网址" />
        </el-form-item>

        <el-form-item label="IP地址" prop="ip">
          <el-input v-model="form.ip" placeholder="请输入IP地址" />
        </el-form-item>

        <el-form-item label="验证状态" align="center" prop="penetrationStatusResult" width="140px"
                      v-show="isShowPenetrationDisabled" >
          <el-select v-model="form.penetrationStatusResult" filterable clearable placeholder="请选择验证状态"
                     :disabled="penetrationDisabled">
            <el-option
                v-for="item in statusList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="验证跟进人" prop="penetrationFollowPerson"
                      v-show="isShowPenetrationDisabled" >
          <el-select v-model="form.penetrationFollowPerson"
                     filterable clearable placeholder="请选择验证跟进人"
                     :disabled="penetrationDisabled"
          >
            <el-option
                v-for="item in penetrationFollowPersonList"
                :key="item.nickName"
                :label="item.nickName"
                :value="item.nickName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="研判跟进人" prop="analysisFollowPerson"
                      v-show="isShowAnalysisDisabled" >
          <el-select v-model="form.analysisFollowPerson"
                     filterable clearable placeholder="请选择研判跟进人"
                     :disabled="analysisDisabled">
            <el-option
                v-for="item in analysisFollowPersonList"
                :key="item.nickName"
                :label="item.nickName"
                :value="item.nickName"

            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="研判状态" prop="analysisStatus"
                      v-show="isShowAnalysisDisabled" >
          <el-select  v-model="form.analysisStatus"
                      filterable
                      clearable
                      placeholder="请选择"
                      :disabled="analysisDisabled">
            <el-option
                v-for="item in analysisStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="后台地址" prop="backend_address"
                      v-show="isShowBackendAddressDisabled" >
          <el-input
              v-model="form.backendAddress"
              :disabled="backendAddressDisabled"
          />
        </el-form-item>


        <el-form-item label="账号" prop="account">
          <el-input
              v-model="form.account"
              placeholder="请输入账号"
              clearable
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="form.password"
              placeholder="请输入密码"
              clearable/>
        </el-form-item>

        <el-form-item label="管理员备注" prop="employerRemark"
                      v-show="isShowEmployerDisabled" >
          <el-input
              v-model="form.employerRemark"
              :disabled="employerDisabled"

          />
        </el-form-item>


        <el-form-item label="验证人员备注" prop="penetrationRemark"
                      v-show="isShowPenetrationDisabledRemark" >
          <el-input
              v-model="form.penetrationRemark"
              :disabled="penetrationDisabledRemark"
          />
        </el-form-item>

        <el-form-item label="研判人员备注" prop="analysisRemark"
                      v-show="isShowAnalysisDisabledRemark" >
          <el-input
              v-model="form.analysisRemark"
              :disabled="analysisDisabledRemark"

          />
        </el-form-item>



        <el-form-item label="是否是主任务" prop="parentTaskRadio">
          <el-radio-group v-model="form.parentTaskRadio">
            <el-radio
                v-for="dict in isMasterTask"
                :key="dict.value"
                :value="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- searchOpen任务对话框 -->
    <el-dialog :title="title" v-model="searchOpen" width="650px" append-to-body :close-on-click-modal="false">
      <el-form ref="taskRef" :model="queryParams"  label-width="120px">
        <el-form-item label="提交单位" prop="source">
          <el-select v-model="queryParams.source" placeholder="请选择提交单位"
                     filterable
                     clearable>
            <el-option
                v-for="dict in sourceList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id">
            </el-option>
          </el-select>

        </el-form-item>

        <el-form-item label="加急状态" prop="priority">
          <el-select v-model="queryParams.priority" placeholder="请选择加急状态">
            <el-option
                v-for="dict in sys_priority"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="地区" prop="value">
          <el-cascader
              placeholder="请输入/选择地区"
              v-model="queryParams.area"
              :options="options"
              @change="handleChange2"
              filterable
              clearable
              :props="{ checkStrictly: true }"
              style="width: 530px">
          </el-cascader>
        </el-form-item>

        <el-form-item label="案件类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择案件类型"
                     filterable
                     clearable>
            <el-option
                v-for="dict in typeList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="提交方内部编号" prop="clientCode">
          <el-input v-model="queryParams.clientCode" placeholder="请输入提交方内部编号" />
        </el-form-item>


        <el-form-item label="URL网址" prop="url">
          <el-input v-model="queryParams.url" placeholder="请输入URL网址" />
        </el-form-item>

        <el-form-item label="IP地址" prop="ip">
          <el-input v-model="queryParams.ip" placeholder="请输入IP地址" />
        </el-form-item>


        <el-form-item label="任务创建时间" prop="createTime">
          <el-date-picker clearable
                          v-model="queryParams.createTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择任务创建时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="验证跟进人" prop="penetrationFollowPerson">
          <el-select v-model="queryParams.penetrationFollowPerson"
                     filterable clearable placeholder="请选择验证跟进人">
            <el-option
                v-for="item in penetrationFollowPersonList"
                :key="item.nickName"
                :label="item.nickName"
                :value="item.nickName">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="验证状态" align="center" prop="penetrationStatusResult" width="140px">
          <el-select v-model="queryParams.penetrationStatusResult" filterable clearable placeholder="请选择验证状态">
            <el-option
                v-for="item in statusList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="验证完成时间" prop="penetrationEndTime">
          <el-date-picker clearable
                          v-model="queryParams.penetrationEndTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择渗透完成时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="研判跟进人" prop="analysisFollowPerson">
          <el-select v-model="queryParams.analysisFollowPerson"
                     filterable clearable placeholder="请选择研判跟进人">
            <el-option
                v-for="item in analysisFollowPersonList"
                :key="item.nickName"
                :label="item.nickName"
                :value="item.nickName">
            </el-option>
          </el-select>

        </el-form-item>

        <el-form-item label="研判状态" prop="analysisStatus">
          <el-select v-model="queryParams.analysisStatus" filterable clearable placeholder="请选择">
            <el-option
                v-for="item in analysisStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="研判完成时间" prop="analysisEndTime">
          <el-date-picker clearable
                          v-model="queryParams.analysisEndTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择研判完成时间">
          </el-date-picker>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleQuery">确 定</el-button>
          <el-button @click="searchOpenCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- searchTaskOpen详情对话框 -->
    <el-dialog :title="title" v-model="searchTaskOpen" width="1150px" append-to-body :close-on-click-modal="false">
      <el-form disabled ref="taskRef" :model="form"  label-width="120px">

        <div style="width: 550px">
        <h3>任务信息：</h3>
        <el-form-item label="加急状态" prop="priority" >
          <el-select v-model="form.priority">
            <el-option
                v-for="dict in sys_priority"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="地区" prop="value">
          <el-cascader
              v-model="form.area"
              :options="options"
              filterable
              clearable
              style="width: 530px"
              :props="{ checkStrictly: true }">
          </el-cascader>
        </el-form-item>

        <el-form-item label="提交单位" prop="source">
          <el-select v-model="form.source" placeholder="请选择提交单位"
                     filterable
                     clearable>
            <el-option
                v-for="dict in sourceList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="案件类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择案件类型"
                     filterable
                     clearable>
            <el-option
                v-for="dict in typeList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="提交方内部编号" prop="clientCode">
          <el-input v-model="form.clientCode" placeholder="请输入提交方内部编号" />
        </el-form-item>


        <el-form-item label="URL网址" prop="url">
          <el-input v-model="form.url" placeholder="请输入URL网址" />
        </el-form-item>

        <el-form-item label="IP地址" prop="ip">
          <el-input v-model="form.ip" placeholder="请输入IP地址" />
        </el-form-item>


        <h3>备注：</h3>
        <el-form-item label="管理员备注" prop="employerRemark">
          <el-input
              v-model="form.employerRemark"
          />
        </el-form-item>

        <el-form-item label="验证人员备注" prop="penetrationRemark">
          <el-input
              v-model="form.penetrationRemark"
          />
        </el-form-item>

        <el-form-item label="研判人员备注" prop="analysisRemark">
          <el-input
              v-model="form.analysisRemark"
          />
        </el-form-item>

        </div>




        <div style="margin-left: 600px;width: 450px;margin-top: -570px">
        <h3>任务状况：</h3>

        <el-form-item label="任务编号" prop="id">
          <el-input v-model="form.id"  />
        </el-form-item>


        <el-form-item label="验证进程" prop="penetrationStatus">
          <el-select
              v-model="form.penetrationStatus"
              placeholder="请选择任务验证进程"
              clearable
              style="width: 240px">
            <el-option
                v-for="dict in sys_hit_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"/>
          </el-select>
        </el-form-item>

        <el-form-item label="验证跟进人" prop="penetrationFollowPerson">
          <el-select v-model="form.penetrationFollowPerson"
                     filterable clearable placeholder="请选择验证跟进人">
            <el-option
                v-for="item in penetrationFollowPersonList"
                :key="item.nickName"
                :label="item.nickName"
                :value="item.nickName">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="验证状态" align="center" prop="penetrationStatusResult" width="140px">
          <el-select v-model="form.penetrationStatusResult" filterable clearable placeholder="请选择验证状态">
            <el-option
                v-for="item in statusList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="验证完成时间" prop="penetrationEndTime">
          <el-date-picker clearable
                          v-model="form.penetrationEndTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择渗透完成时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="研判进程" prop="analysisStatus">
          <el-select
              v-model="form.analysisStatus"
              placeholder="请选择任务研判进程"
              clearable
              style="width: 240px">
            <el-option
                v-for="dict in analysisStatusList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"/>
          </el-select>
        </el-form-item>



        <el-form-item label="研判跟进人" prop="analysisFollowPerson">
          <el-select v-model="form.analysisFollowPerson"
                     filterable clearable placeholder="请选择研判跟进人">
            <el-option
                v-for="item in analysisFollowPersonList"
                :key="item.nickName"
                :label="item.nickName"
                :value="item.nickName">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="研判状态" prop="analysisStatus">
          <el-tag v-if="form.analysisStatus == 2">{{ "-----" }}</el-tag>
          <el-tag type="danger" v-else-if="form.analysisStatus == 0">{{ "未完成" }}</el-tag>
          <el-tag type="success" v-else-if="form.analysisStatus == 1">{{ "已完成" }}</el-tag>
        </el-form-item>


        <el-form-item label="研判完成时间" prop="analysisEndTime">
          <el-date-picker clearable
                          v-model="form.analysisEndTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择研判完成时间">
          </el-date-picker>
        </el-form-item>





        <el-form-item label="任务创建时间" prop="createTime">
          <el-date-picker clearable
                          v-model="form.createTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择任务创建时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="任务创建人" prop="createBy">
          <el-input
              v-model="form.createBy"
          />
        </el-form-item>


        <el-form-item label="后台地址" prop="backend_address">
          <el-input
              v-model="form.backendAddress"
          />
        </el-form-item>


        <el-form-item label="账号" prop="account">
          <el-input
              v-model="form.account"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="form.password"
          />
        </el-form-item>
        </div>




      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <!--          <el-button type="primary" @click="handleQuery">确 定</el-button>-->
          <el-button @click="searchTaskOpenCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>



    <!-- taskDetailOpen详情对话框 -->
    <el-dialog :title="title" v-model="taskDetailOpen" width="1050px" append-to-body :close-on-click-modal="false">
      <el-form v-if="title=='主任务' || title=='子任务-已关联'" ref="taskRef" :model="form"  label-width="150px">


        <el-table v-loading="loading" :data="taskDetailList" @selection-change="handleSelectionChange">
          <!--          <el-table-column type="selection" width="55" align="center" />-->
          <el-table-column label="任务编号" align="center" prop="id" fixed width="180px">
            <template #default="scope">

          <span>
            <el-tag type="success" v-if="scope.row.parentTaskRadio==0">主任务</el-tag>
            <el-tag type="danger"  v-else-if="scope.row.parentTaskRadio==-1 && scope.row.parentTaskId==-1">子任务-未关联</el-tag>
            <el-tag  v-else-if="scope.row.parentTaskRadio==-1 && scope.row.parentTaskId!=-1">子任务-已关联</el-tag>

            {{scope.row.id}}
          </span>

            </template>
          </el-table-column>
          <el-table-column label="URL地址" align="center" prop="url" width="170px" fixed />

          <el-table-column label="验证进程" align="center" prop="penetrationStatus">
            <template #default="scope">
              <dict-tag :options="sys_hit_status" :value="scope.row.penetrationStatus" />
            </template>
          </el-table-column>

          <el-table-column label="验证跟进人" align="center" prop="penetrationFollowPerson" />

          <el-table-column label="验证状态" align="center" prop="penetrationStatusResult" width="150px">
            <template #default="scope">
              <el-tag >{{ getStatusName(scope.row.penetrationStatusResult) }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="验证完成时间" align="center" prop="penetrationEndTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.penetrationEndTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>

          <el-table-column label="研判进程" align="center" prop="analysisStatus" >
            <template #default="scope">
              <dict-tag :options="sys_hit_status" :value="scope.row.analysisStatus"/>
            </template>
          </el-table-column>

          <el-table-column label="研判跟进人" align="center" prop="analysisFollowPerson" />

          <el-table-column label="研判状态" align="center" prop="analysisStatus">
            <template #default="scope">
              <el-tag v-if="scope.row.analysisStatus == 2">{{ "-----" }}</el-tag>
              <el-tag type="danger" v-else-if="scope.row.analysisStatus == 0">{{ "未完成" }}</el-tag>
              <el-tag type="success" v-else-if="scope.row.analysisStatus == 1">{{ "已完成" }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="研判完成时间" align="center" prop="analysisEndTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.analysisEndTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>


          <el-table-column label="省份" align="center" prop="province" />
          <el-table-column label="城市" align="center" prop="city" />
          <el-table-column label="区县" align="center" prop="county" />

          <el-table-column label="案件类型" align="center" width="120px" prop="type" >
            <template #default="scope">
              <el-tag >{{ getName(scope.row.type) }}</el-tag>
              <!--          {{ getName(scope.row.type) }}-->
            </template>
          </el-table-column>

          <el-table-column label="IP地址" align="center" prop="ip" width="120px"/>
          <el-table-column label="任务创建时间" align="center" prop="createTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="任务创建人" align="center" prop="createBy" />

          <el-table-column label="加急状态" align="center" prop="priority" fixed="right">
            <template #default="scope">
              <dict-tag :options="sys_priority" :value="scope.row.priority" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100px" fixed="right">
            <template #default="scope">
              <!--              <el-button link type="primary" icon="Edit" @click="handleDetails(scope.row)" v-hasPermi="['system:task:edit']">关联</el-button>-->
              <!--              <el-button link type="primary" icon="Edit" @click="handleSearch(scope.row)" v-hasPermi="['system:task:edit']">查看</el-button>-->
              <!--              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:task:edit']">修改</el-button>-->
              <el-button v-if="scope.row.parentTaskRadio==-1" link type="primary" icon="Delete" @click="deleteSubTask(scope.row)" v-hasPermi="['system:task:remove']">取消关联</el-button>
            </template>
          </el-table-column>
        </el-table>

<!--        <pagination-->
<!--            v-show="total>0"-->
<!--            :total="total"-->
<!--            v-model:page="queryParams.pageNum"-->
<!--            v-model:limit="queryParams.pageSize"-->
<!--            @pagination="getList"-->
<!--        />-->

      </el-form>


      <el-form v-if="title=='子任务-未关联'"  ref="taskRef" :model="subTaskForm"  label-width="150px">

        <el-form-item label="请选择主任务编号" prop="source">
          <el-select v-model="subTaskForm.parentTaskId" placeholder="请选择"
                     filterable
                     clearable>
            <el-option
                v-for="dict in masterTaskListValue"
                :key="dict.id"
                :label="dict.id"
                :value="dict.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitTaskDetail(title)">添 加</el-button>
          <el-button @click="taskDetailCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>




    <el-dialog :title="upload.title" v-model="upload.open" width="400px"  append-to-body :close-on-click-modal="false">
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          action="#"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
          :http-request="uploadFile"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">拖拽文件到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <!--            <div class="el-upload__tip">-->
            <!--              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据-->
            <!--            </div>-->
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Task">
import { listTask, getTask, delTask, addTask, updateTask,masterTaskList,
  bindMasterTask,editContactTask, againGetIpFuntion, getUserInfo,getMasterOrSubTask,uploadFile2 } from "@/api/system/task";
import VDistpicker from 'v-distpicker';
const { proxy } = getCurrentInstance();
const { sys_hit_status, sys_priority,sys_task_status } = proxy.useDict("sys_hit_status","sys_priority","sys_task_status");
// const { data, province, city, area, town } = require("province-city-china/data");
import dataArea from 'province-city-china/dist/level.json'
import { ref, onMounted,computed } from 'vue'
import { listAllSource } from "@/api/system/source";
import { listAllType } from "@/api/system/type";
import { allListByType } from "@/api/system/status";
import { getListByRole } from "@/api/system/user";
import { getToken } from "@/utils/auth";
import {blobValidate} from "@/utils/ruoyi.js";
import errorCode from "@/utils/errorCode.js";
import {ElLoading, ElMessage} from "element-plus";
let downloadLoadingInstance;

const multipleTableRef = ref([]);
const fileRef = ref(null);

//控制禁用
const backendAddressDisabled = ref(true);
const employerDisabled = ref(true);
const penetrationDisabled = ref(true);
//验证跟进人备注
const penetrationDisabledRemark = ref(true);
const analysisDisabled = ref(true);
//研判人员备注
const analysisDisabledRemark = ref(true);


//下面6个控制显示
const isShowBackendAddressDisabled = ref(false);
const isShowEmployerDisabled = ref(false);
const isShowPenetrationDisabled = ref(false);
//验证跟进人备注
const isShowPenetrationDisabledRemark = ref(false);
const isShowAnalysisDisabled = ref(false);
//研判人员备注
const isShowAnalysisDisabledRemark = ref(false);


const changeListButton = ref(true);
const taskList = ref([]);
const taskDetailList = ref([]);
const open = ref(false);
const addSubTask = ref(false);
const searchOpen = ref(false);
const searchTaskOpen = ref(false);
const taskDetailOpen = ref(false);
const importOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const addTaskButton = ref(true);
const deleteTaskButton = ref(true);
const againGetIpButton = ref(true);
const total = ref(0);
const title = ref("");
const title2 = ref("");
const dateRange = ref([]);
const value = ref([]);
const options = ref([]);
const sourceList = ref([]);
const typeList = ref([]);
const statusList = ref([]);
const analysisFollowPersonList = ref([]);
const userInfoList = ref([]);
const penetrationFollowPersonList = ref([]);
const masterTaskListValue = ref([]);
const subTaskListValue = ref([]);
const analysisStatusList = ref([{
  value: 0,
  label: '未完成'
}, {
  value: 1,
  label: '已完成'
}, {
  value: 2,
  label: '进行中'
}]);

/*** 任务导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: {
    Authorization: "Bearer " + getToken() ,
},
  responseType: 'blob',
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/task/importData"
});

const isMasterTask = ref([{
  value: 0,
  label: '是'
}, {
  value: -1 ,
  label: '不是'
}]);

const handleChange = (value) => {
  if(value != null){
    switch (value.length){
      case 1:
        queryParams.value.province = value[0]
        queryParams.value.city = null
        queryParams.value.county = null
        break;
      case 2:
        queryParams.value.province = value[0]
        queryParams.value.city = value[1]
        queryParams.value.county = null
        break;
      case 3:
        queryParams.value.province = value[0]
        queryParams.value.city = value[1]
        queryParams.value.county = value[2]
    }
  }

  getList()

}




const handleChange2 = (value) => {
  if(value != null) {
    switch (value.length) {
      case 1:
        queryParams.value.province = value[0]
        queryParams.value.city = null
        queryParams.value.county = null
        break;
      case 2:
        queryParams.value.province = value[0]
        queryParams.value.city = value[1]
        queryParams.value.county = null
        break;
      case 3:
        queryParams.value.province = value[0]
        queryParams.value.city = value[1]
        queryParams.value.county = value[2]
    }
  }
}

const isVisible = ref(false);

const handleChange3 = (value) => {
  if(value != null) {
    switch (value.length) {
      case 1:
        form.value.province = value[0]
        form.value.city = null
        form.value.county = null
        break;
      case 2:
        form.value.province = value[0]
        form.value.city = value[1]
        form.value.county = null
        break;
      case 3:
        form.value.province = value[0]
        form.value.city = value[1]
        form.value.county = value[2]
    }


      const totalLevels = getTotalLevels(options.value);
      if (value.length === totalLevels) {
        // Automatically close el-cascader

        console.log(value.length)
        console.log(totalLevels)

        isVisible.value = false;
      }


  }

}


const getSelectChangeList = (value) => {
  getList()
}

const handleVisibleChange = (visible) => {
  isVisible.value = visible;
};

// Watch for changes in visibility and close the component if needed
watch(isVisible, (visible) => {
  if (!visible) {
    // Optionally, you can perform any action needed when the component is closed
  }
});


const dataList = dataArea

const getAreaCode = (nodeId) => {
  const parents = findAllParents(
      dataList,
      { code: nodeId },
      (item, node) => item.code === node.code
      // {
      //   props: {
      //     children: 'child'
      //   }
      // }
  )

  let codes = []
  let names = []

  for (let node of parents) {
    codes.push(node.code)
    names.push(node.name)
  }

  codes.push(nodeId)
  let dataArea = { codes: codes, names: names }
  return dataArea
}

//json.js
const defaults = {
  props: {
    children: 'children'
  }
}


const findParent = (dataArea, node, predicate, options = {}) => {
  let config = Object.assign({}, defaults, options)

  let parent = undefined
  for (let i = 0; i < dataArea.length; i++) {
    if (parent) return parent

    let item = dataArea[i]

    if (item[config.props.children] && item[config.props.children].length > 0) {
      let child = item[config.props.children].filter((c) => predicate(c, node))
      if (child.length > 0) {
        parent = item
      }

      if (parent === undefined) {
        parent = findParent(item[config.props.children], node, predicate, config)
      } else {
        break
      }
    }
  }
  return parent
}

const findAllParents = (dataArea, node, predicate, options = {}) => {
  let config = Object.assign({}, defaults, options)

  let allParents = []
  let parent = findParent(dataArea, node, predicate, config)
  while (parent !== undefined) {
    allParents.unshift(parent)
    parent = findParent(dataArea, parent, predicate, config)
  }
  return allParents
}

onMounted(() => {

  listAllSource(queryParams.value).then(response => {
    sourceList.value = response.rows;
  });

  listAllType(queryParams.value).then(response => {
    typeList.value = response.rows;
  });

  queryParams.value.statusType  = 1
  allListByType(queryParams.value).then(response => {
    statusList.value = response.rows;
  });


  queryParams.value.roleName  = "研判跟进人"
  getListByRole(queryParams.value).then(response => {
    analysisFollowPersonList.value = response.rows;
  });

  queryParams.value.roleName  = "验证跟进人"
  getListByRole(queryParams.value).then(response => {
    penetrationFollowPersonList.value = response.rows;
  });
  queryParams.value.roleName  = null
  queryParams.value.statusType  = null


  // queryParams.value.parentTaskRadio = 0
  // masterTaskList(queryParams.value).then(response => {
  //   //主任务list
  //   masterTaskListValue.value = response.rows;
  // });
  // queryParams.value.parentTaskRadio = null
  // queryParams.value.parentTaskId = null


  // queryParams.value.parentTaskRadio = -1
  // masterTaskList(queryParams.value).then(response => {
  //   //子任务list
  //   subTaskListValue.value = response.rows;
  // });
  // queryParams.value.parentTaskRadio = null
  // queryParams.value.parentTaskId = null







  getUserInfo().then(response => {
    for (let i = 0; i < response.rows.length; i++) {
      userInfoList.value.push(response.rows[i].roleName)

      if (userInfoList.value.findIndex((v)=>{
        return v==="研判跟进人"
      })!==-1){
        analysisDisabled.value= false
        analysisDisabledRemark.value= false

        isShowAnalysisDisabled.value = true
        isShowAnalysisDisabledRemark.value = true

      }

      if (userInfoList.value.findIndex((v)=>{
        return  v==="验证跟进人"
      })!==-1){
        penetrationDisabled.value= false
        penetrationDisabledRemark.value= false
        backendAddressDisabled.value= false

        isShowPenetrationDisabled.value = true
        isShowPenetrationDisabledRemark.value =true
        isShowBackendAddressDisabled.value = true
      }

      if (
          userInfoList.value.findIndex((v)=>(v==="普通管理员"|| v==="超级管理员")) !==-1)
      {
        changeListButton.value=false
        employerDisabled.value= false
        penetrationDisabled.value= false
        analysisDisabled.value= false
        backendAddressDisabled.value= false

        isShowAnalysisDisabled.value = true
        isShowPenetrationDisabled.value = true
        isShowEmployerDisabled.value = true
        isShowBackendAddressDisabled.value = true
      }
    }
    // userInfoList.value = response.rows.map(v => v.roleName)
    // analysisDisabled.value = userInfoList.value.includes('研判跟进人')
    // penetrationDisabled.value = userInfoList.value.includes('渗透跟进人')
    // employerDisabled.value =
    //     userInfoList.value.includes('普通管理员') ||
    //     userInfoList.value.includes('超级管理员')
  });


  options.value = dataArea
  options.value = options.value.map((item) => {
    return {
      value: item.name,
      label: item.name,
      children: item.children?.map((item2) => {
        return {
          value: item2.name,
          label: item2.name,
          children: item2.children?.map((item3) => {
            return {
              value: item3.name,
              label: item3.name
            }
          })
        }
      })
    }
  })
  value.value = getAreaCode('420106').codes
})



const data = reactive({
  selectFormById:{},
  subTaskForm:{},
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    priority: null,
    source: null,
    province: null,
    city: null,
    county: null,
    type: null,
    clientCode: null,
    url: null,
    ip: null,
    penetrationEndTime: null,
    analysisEndTime: null,
    penetrationStatus: null,
    analysisStatus: null,
    penetrationFollowPerson: null,
    analysisFollowPerson: null,
    backendAddress: null,
    account: null,
    password: null,
    employerRemark: null,
    penetrationRemark: null,
    analysisRemark: null,
    penetrationStatusResult:null,
    roleName:null,
    parentTaskId:null,
    //0.自己数据，1所有数据
    allOrMyData:0
  },
  statusParams:{
  },
  rules: {
    source: [{ required: true, message: "提交单位不能为空", trigger: "change" }],
    priority: [{ required: true, message: "加急状态不能为空", trigger: "change" }],
    type: [{ required: true, message: "案件类型不能为空", trigger: "change" }],
    url: [{ required: true, message: "URL地址不正确", trigger: "blur", pattern:"^(https?:\\/\\/)?(www\\.)?([a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+)(:[0-9]{1,5})?(\\/.*)?$" }],
  }
});

const { queryParams, form, rules ,subTaskForm,selectFormById  } = toRefs(data);

const getName = computed(() => id => {
  const obj = typeList.value.find(v => v.id == id)
  return obj?.name || '--'
})

const getStatusName = computed(() => id => {
  const obj = statusList.value.find(v => v.id == id)
  return obj?.name || '--'
})

/** 查询任务列表 */
function getList() {
  loading.value = true;
  if (queryParams.value.area == null){
    queryParams.value.province = null
    queryParams.value.city = null
    queryParams.value.county = null
  }
  listTask(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    taskList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });

}


// 取消按钮
function cancel() {
  open.value = false;
  queryParams.value.province = null
  queryParams.value.city = null
  queryParams.value.county = null
  reset();
}


function subTaskCancel() {
  addSubTask.value = false;
  reset();
  subTaskForm.value.parentTaskId=null
}

function taskDetailCancel() {
  taskDetailOpen.value = false;
  reset();
  subTaskForm.value.parentTaskId=null
  subTaskForm.value.subTaskIds = null
}

function submitTaskDetail(taskName) {

  //数据量过大
  // queryParams.value.parentTaskRadio = -1
  // masterTaskList(queryParams.value).then(response => {
  //   //子任务list
  //   subTaskListValue.value = response.rows;
  // });



  queryParams.value.parentTaskRadio = null
  queryParams.value.parentTaskId = null
  subTaskForm.value.subTaskIds = null

  if (taskName == "子任务-未关联"){
    subTaskForm.value.subTaskIds = [form.value.id]
    bindMasterTask(subTaskForm.value).then(response => {
      proxy.$modal.msgSuccess("任务关联成功");
      taskDetailOpen.value = false;
      getList();
      subTaskForm.value.parentTaskId=null
      subTaskForm.value.subTaskIds=null
    });
  }else{
    //出现子任务list
    // reset();
    subTaskForm.value.parentTaskId = null
    title2.value = "主任务关联";
    addSubTask.value = true;
  }

}




//任务绑定主任务
function submitSubTask(title2) {

  if (title2=="子任务关联"){
    //子任务关联父任务
    subTaskForm.value.subTaskIds = ids.value

  }else if (title2=="主任务关联"){
    //父任务关联子任务
    // subTaskForm.value.subTaskIds = taskDetailList.value[0].id
    subTaskForm.value.parentTaskId = taskDetailList.value[0].id
    subTaskForm.value.subTaskIds = subTaskForm.value.subTaskIds.split(',')

// //存储转换后的整数数组
//     const intArray = ref([]);
// // 方法：将输入的字符串转换为整数数组
//       intArray.value = subTaskForm.value.subTaskIds.split(',') // 用逗号分隔字符串
//           .map(str => str.trim()) // 去除每个数值的前后空白
//           .filter(str => !isNaN(str) && str !== '') // 过滤掉非数字和空字符串
//           .map(Number); // 将每个字符串转换为整数
//     console.log(intArray)
  }

  bindMasterTask(subTaskForm.value).then(response => {
    proxy.$modal.msgSuccess("任务关联成功");
    addSubTask.value = false;

    if (title2=="子任务关联"){
      getList();
    }else {
      handleDetailsByFresh(selectFormById.value.id)
    }


    subTaskForm.value.parentTaskId=null
    subTaskForm.value.subTaskIds=null
    subTaskForm.value.parentTaskRadio=null
  });
}


// 任务取消关联
function deleteSubTask(row) {

  if(ids.value.length>0){
    subTaskForm.value.subTaskIds = ids.value
  }else {
    subTaskForm.value.subTaskIds = [row.id]
  }

  proxy.$modal.confirm('是否确认取消任务编号为"' + subTaskForm.value.subTaskIds + '"关联？').then(function() {
    return editContactTask(subTaskForm.value);
  }).then(() => {
    getList();
    taskDetailOpen.value = false;
    proxy.$modal.msgSuccess("关联任务取消成功");
  }).catch(() => {});

  // form.value.subTaskIds = ids.value
  // editContactTask(form.value).then(response => {
  //   proxy.$modal.msgSuccess("取消成功");
  //   getList();
  // });
}


// Ip重新获取
function againGetIp(type) {

  if (type == 'signle'){
    subTaskForm.value.subTaskIds = ids.value
  }
  subTaskForm.value.againType = type
  againGetIpFuntion(subTaskForm.value).then(response => {
    proxy.$modal.msgSuccess("ip重新获取成功");
    getList();
    subTaskForm.value.subTaskIds=null
    subTaskForm.value.againType=null
  });

}

//数据切换
function changeList() {
  loading.value = true;
  if (queryParams.value.allOrMyData==0){
    queryParams.value.allOrMyData=1
  }else {
    queryParams.value.allOrMyData=0
  }
  listTask(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    taskList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });


}





function searchTaskOpenCancel() {
  searchTaskOpen.value = false;
  searchOpenReset();
}



function searchOpenCancel() {
  searchOpen.value = false;
  searchOpenReset();
}



// 查询表单重置
function searchOpenReset() {
  queryParams.value= {
    pageNum: 1,
    pageSize: 10,
    priority: null,
    source: null,
    province: null,
    city: null,
    county: null,
    type: null,
    clientCode: null,
    url: null,
    ip: null,
    penetrationEndTime: null,
    analysisEndTime: null,
    penetrationStatus: null,
    analysisStatus: null,
    penetrationFollowPerson: null,
    analysisFollowPerson: null,
    backendAddress: null,
    account: null,
    password: null,
    employerRemark: null,
    penetrationRemark: null,
    analysisRemark: null,
    penetrationStatusResult:null,
    roleName:null,
    createTime:null,
    subTaskIds:null,
    allOrMyData:0
  };
  proxy.resetForm("taskRef");
}


// 表单重置
function reset() {
  form.value = {
    id: null,
    priority: null,
    source: null,
    province: null,
    city: null,
    county: null,
    type: null,
    clientCode: null,
    url: null,
    ip: null,
    penetrationEndTime: null,
    analysisEndTime: null,
    penetrationStatus: null,
    analysisStatus: null,
    penetrationFollowPerson: null,
    analysisFollowPerson: null,
    backendAddress: null,
    account: null,
    password: null,
    employerRemark: null,
    penetrationRemark: null,
    analysisRemark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    penetrationStatusResult:null,
    parentTaskRadio:null,
  };
  proxy.resetForm("taskRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
  searchOpen.value = false;
}

/** 重置按钮操作 */
function resetQuery() {
  searchOpenReset();
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  addTaskButton.value = !selection.length;
  deleteTaskButton.value = !selection.length;
  againGetIpButton.value = !selection.length;

}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加任务";
}

/** 关联任务 */
function subTask() {
  reset();
  subTaskForm.value.parentTaskId = null
  addSubTask.value = true;
  title2.value = "子任务关联";

  queryParams.value.parentTaskRadio = 0
  masterTaskList(queryParams.value).then(response => {
    //主任务list
    masterTaskListValue.value = response.rows;
  });
  queryParams.value.parentTaskRadio = null
  queryParams.value.parentTaskId = null
}


/** searchOpen按钮操作 */
function handleTaskSearch() {
  reset();
  searchOpen.value = true;
  title.value = "查询任务（非每项必填）";
}


/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getTask(_id).then(response => {
    form.value = response.data;
    form.value.priority =  response.data.priority + ''

    if (form.value.province!==null && form.value.city!==null && form.value.county !==null ){
      form.value.area = ref([ form.value.province,form.value.city,form.value.county]); // 示例值
    }else if (form.value.province!==null && form.value.city!==null){
      form.value.area = ref([ form.value.province,form.value.city]); // 示例值
    }else {
      form.value.area = ref([ form.value.province]); // 示例值
    }
    open.value = true;
    title.value = "修改任务";
  });
}

/** 查看按钮操作 */
function handleSearch(row) {
  reset();
  const _id = row.id || ids.value
  getTask(_id).then(response => {
    form.value = response.data;
    form.value.priority = response.data.priority + ''
    form.value.penetrationStatus = response.data.penetrationStatus + ''
    if (form.value.province!==null && form.value.city!==null && form.value.county !==null ){
      form.value.area = ref([ form.value.province,form.value.city,form.value.county]); // 示例值
    }else if (form.value.province!==null && form.value.city!==null){
      form.value.area = ref([ form.value.province,form.value.city]); // 示例值
    }else {
      form.value.area = ref([ form.value.province]); // 示例值
    }


    searchTaskOpen.value = true;
    title.value = "任务详情";
  });
}


/** 任务关联按钮操作 */
function handleDetails(row) {
  reset();


  form.value.id = row.id
  queryParams.value.parentTaskRadio = 0
  masterTaskList(queryParams.value).then(response => {
    //主任务list
    masterTaskListValue.value = response.rows;
  });



  subTaskForm.value.parentTaskId=null
  const _id = row.id || ids.value

  selectFormById.value.id = _id

  getMasterOrSubTask(_id).then(response => {
    taskDetailList.value = response.data;

    // form.value.priority = response.data.priority + ''
    // form.value.penetrationStatus = response.data.penetrationStatus + ''
    // form.value.area = ref([form.value.province, form.value.city, form.value.county]); // 示例值
  });
  if (row.parentTaskRadio==0){
    title.value = "主任务";
  }else if (row.parentTaskRadio==-1 && row.parentTaskId !=-1){
    title.value = "子任务-已关联";
  }else {
    title.value = "子任务-未关联"
  }
  queryParams.value.parentTaskRadio = null
  queryParams.value.parentTaskId = null
  taskDetailOpen.value = true;

  // const _id = row.id || ids.value
  // getTask(_id).then(response => {
  //   form.value = response.data;
  //   form.value.priority =  response.data.priority + ''
  //   form.value.penetrationStatus =  response.data.penetrationStatus + ''
  //   form.value.area = ref([ form.value.province,form.value.city,form.value.county]); // 示例值
  // }
  // );

}

/** 任务关联按钮操作 */
function handleDetailsByFresh(row) {
  getList()
  reset();
  const _id = row


  getMasterOrSubTask(_id).then(response => {
    taskDetailList.value = response.data;
    form.value.id = row.id
    // form.value.priority = response.data.priority + ''
    // form.value.penetrationStatus = response.data.penetrationStatus + ''
    // form.value.area = ref([form.value.province, form.value.city, form.value.county]); // 示例值
  });
  taskDetailOpen.value = true;

  // const _id = row.id || ids.value
  // getTask(_id).then(response => {
  //   form.value = response.data;
  //   form.value.priority =  response.data.priority + ''
  //   form.value.penetrationStatus =  response.data.penetrationStatus + ''
  //   form.value.area = ref([ form.value.province,form.value.city,form.value.county]); // 示例值
  // }
  // );

}


function handleImport() {
  upload.title = "Excel导入";
  upload.open = true;
}



/** 提交按钮 */
function submitForm() {
  proxy.$refs["taskRef"].validate(valid => {

    console.log()(valid)

    if (valid) {
      if (form.value.id != null) {
        updateTask(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          queryParams.value.province = null
          queryParams.value.city = null
          queryParams.value.county = null
          getList();
        });
      } else {
        addTask(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          queryParams.value.province = null
          queryParams.value.city = null
          queryParams.value.county = null

          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除任务编号为"' + _ids + '"的数据项？').then(function() {
    return delTask(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  queryParams.value.subTaskIds = ids.value
  // queryParams.value.allOrMyData = ids.value
  // q
  proxy.download('system/task/export', {
    ...queryParams.value
  }, `task_${new Date().getTime()}.xlsx`)

  queryParams.value.subTaskIds = null
}


/** 下载模板操作 */
function importTemplate() {
  proxy.download("system/task/importTemplate", {
  }, `task_template_${new Date().getTime()}.xlsx`);
};

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  alert("正在上传")
  upload.open = false;
  downloadLoadingInstance = ElLoading.service({ text: "正在上传文件数据，请稍候", background: "rgba(0, 0, 0, 0.7)", })
  upload.isUploading = true;

};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);

  if (response=="导入成功！"){
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response + "</div>", "数据导入成功", { dangerouslyUseHTMLString: true });
  }else {
    //导出
    downloadLoadingInstance = ElLoading.service({ text: "正在下载数据，请稍候", background: "rgba(0, 0, 0, 0.7)", })
    // const isBlob = blobValidate(response);
    // if (isBlob) {
      // const blob = new Blob([response], {
      //   type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' // 设置Excel文件类型
      // });
      // saveAs(blob, `task_${new Date().getTime()}.xlsx`)

      // 创建一个下载链接并触发下载
      // const url = window.URL.createObjectURL(new Blob([response],{
      //   type : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      // }));
      //
      // const link = document.createElement('a');
      // link.href = url;
      // link.setAttribute('download', 'filename.xlsx'); // 文件名
      // document.body.appendChild(link);
      // link.click();
      // document.body.removeChild(link);
    // } else {
    //   const resText =  response.text();
    //   const rspObj = JSON.parse(resText);
    //   const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
    //   ElMessage.error(errMsg);
    // }
    downloadLoadingInstance.close();
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + "结果详情请看excel" + "</div>", "有部分数据导入失败", { dangerouslyUseHTMLString: true });
  }

getList();
};

const currentDate = ref(new Date());
const year = ref(currentDate.value.getFullYear());
const month = ref(currentDate.value.getMonth() + 1); // 月份从0开始
const day = ref(currentDate.value.getDate());

function uploadFile(item) {
  // 开始上传文件 新建一个formData
  const formData = new FormData();
  // 通过append向form对象添加数据
  formData.append("file", item.file);
  uploadFile2(formData)
      .then((data) => {
        upload.open = false;
        upload.isUploading = false;
        proxy.$refs["uploadRef"].handleRemove(item.file);

        if (data.size<=0){
          proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + "数据导入成功" + "</div>", "数据导入成功", { dangerouslyUseHTMLString: true });
        }else {
          // 使用 ElMessageBox 询问用户是否要下载错误数据文件
          proxy.$confirm(
              "导入过程中有部分数据失败，是否下载错误数据文件？",
              "导入失败",
              {
                confirmButtonText: "下载",
                cancelButtonText: "取消",
                type: "warning",
              }
          ).then(() => {
                // 用户确认下载时执行下载操作
            //导出
            downloadLoadingInstance = ElLoading.service({ text: "正在下载数据，请稍候", background: "rgba(0, 0, 0, 0.7)", })
            const blob = new Blob([data])
            saveAs(blob, '导入失败的数据_'+year.value+'_'+month.value+'_'+day.value+'.xlsx')
            downloadLoadingInstance.close();
                proxy.$alert(
                    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>结果详情请看excel</div>",
                    "有部分数据导入失败",
                    { dangerouslyUseHTMLString: true }
                );
              })
              .catch(() => {
                // 用户取消下载时处理
                proxy.$message({
                  type: "info",
                  message: "下载已取消",
                });
              })
        }

          getList();
      }).catch((e) => {
        console.log("上传失败");
        this.clearFlies();
      });
}


/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};



function rowClick(row, column, event) {

  multipleTableRef.value.toggleRowSelection(row, undefined)

};



// 复制站点信息
function onCopy(text, index) {
  if (navigator.clipboard && window.isSecureContext) {
    navigator.clipboard.writeText(text);
    ElMessage.success('复制成功')
  } else {
    // 创建text area
    let textArea = document.createElement("textarea");
    textArea.value = text;
    // 使text area不在viewport，同时设置不可见
    textArea.style.position = "absolute";
    textArea.style.opacity = 0;
    textArea.style.left = "-999999px";
    textArea.style.top = "-999999px";
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    ElMessage.success('复制成功')
    return new Promise((res, rej) => {
      // 执行复制命令并移除文本框
      document.execCommand('copy') ? res() : rej();
      textArea.remove();
    });
  }
  return
  const item = '#copyText' + index
  const clipboard = new Clipboard(item, {
    text: () => text
  })

  clipboard.on('success', (e) => {
    ElMessage.success('复制成功')
    e.clearSelection()
  })

  clipboard.on('error', () => {
    ElMessage.error('复制失败')
  })
}



const getTotalLevels = (options) => {
  const getLevels = (options) => {
    let maxLevel = 1;
    for (const option of options) {
      if (option.children && option.children.length) {
        maxLevel = Math.max(maxLevel, 1 + getLevels(option.children));
      }
    }
    return maxLevel;
  };
  return getLevels(options);
};




//列表查询
getList();
</script>

<style>

.el-select__selected-item {
  user-select: all !important;
}
</style>
